package com.lc.file.controller;

import cn.hutool.core.util.IdUtil;
import com.lc.file.utils.UploadUtil;
import com.study.common.constant.LocalConstant;
import com.study.common.res.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * @description: some desc
 * @author: LChuang
 * @date: 2023/9/8 11:49
 */
@Slf4j
@RestController
@RequestMapping(value = "/file/upload")
public class FileUploadController {

    @PostMapping(value = "/uploads")
    public ApiResult uploads(HttpServletRequest request, @RequestParam("files") MultipartFile[] files) {
        String fileName = "";
        try {
            //上传目录地址
            String uploadDir = LocalConstant.LOCAL_UPLOAD_PATH;
            // 目录如果不存在则创建
            File file = new File(uploadDir);
            if (!file.isDirectory()) {
                file.mkdir();
            }
            //遍历文件数组执行上传
            for (MultipartFile mf : files) {
                if (mf != null) {
                    //调用上传方法
                    fileName = UploadUtil.executeUpload(uploadDir, mf);
                    log.info("{}文件上传完成，文件路径：{}", fileName, uploadDir);
                }
            }
            return ApiResult.success();
        } catch (Exception e) {
            log.error("文件上传出现异常：{}", e.getMessage());
            return ApiResult.fail(e.getMessage());
        }
    }
}
